<template>
  <el-card :shadow="'never'" style="border: none">
    <el-row :gutter="20">
      <el-col :span="18" style="text-align: left"
        ><el-input
          v-model="val"
          placeholder="请输入名称"
          :prefix-icon="Search"
          class="input-with-select"
      /></el-col>

      <el-col
        :span="4"
        style="
          padding-left: 0;
          cursor: pointer;
          display: flex;
          align-items: center;
          font-size: larger;
        "
      >
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="status === 'expand' ? '展开' : '收缩'"
          placement="top"
        >
          <el-icon
            ><Expand v-if="status === 'expand'" @click="click('fold')" /><Fold
              v-else
              @click="click('expand')"
          /></el-icon>
        </el-tooltip>
      </el-col>
    </el-row>

    <el-tree
      ref="treeRef"
      style="margin-top: 15px"
      :data="data"
      node-key="id"
      highlight-current
      :current-node-key="choose"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      @current-change="currentChange"
    >
      <template #default="{ data }">
        <component :is="useRenderIcon(toRaw(data.icon))" />&nbsp;{{
          data.title
        }}
      </template>
    </el-tree>
  </el-card>
</template>

<script lang="ts" setup name="sys-acl-tree">
import { NzSafeAny } from "@/components/sf/type";
import { Http } from "@/core/api/http.service";
import { Search, Fold, Expand } from "@element-plus/icons-vue";
import { ElTree } from "element-plus";
import { ref, toRaw, watch } from "vue";
import { useRenderIcon } from "@/components/icon/src/hooks";
type TreeMenu = {
  id: string;
  label: string;
  children: TreeMenu[];
  disabled: boolean;
};
const emits = defineEmits(["check"]);
const treeRef = ref<InstanceType<typeof ElTree>>();
const val = ref("");
const status = ref("expand");
const choose = ref<string>("all");
const data = ref<TreeMenu[]>([]);
watch(val, (res: string) => {
  if (treeRef.value) {
    treeRef.value!.filter(res);
  }
});
const click = (key: string) => {
  status.value = key;
  if (key === "fold") {
    Object.values(treeRef.value!.store.nodesMap).forEach(v => v.expand());
  } else {
    Object.values(treeRef.value!.store.nodesMap).forEach(v => v.collapse());
  }
};
const currentChange = (node: any) => {
  choose.value = node?.id;
  emits("check", node);
};
const filterNode = (value: string, data: NzSafeAny) => {
  if (!value) return true;
  return data.title?.includes(value);
};
Http.of()
  .get(`/lc-system/department/tree/list`)
  .then((r: NzSafeAny) => {
    data.value = [
      { id: "all", title: "全部", icon: "material-symbols:border-all" },
      ...(r || [])
    ];
  });
</script>
@/components/sf/types
